package com.hy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hy.core.request.ApiRequestDTO;
import com.hy.core.response.ApiResponseDTO;
import com.hy.utils.RSA;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

public class HandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成之后
        super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 处理器执行完毕之后
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理器实际执行之前

        // equalsIgnoreCase 与 equals的区别？
//        if("GET".equalsIgnoreCase(request.getMethod())){
//            return false;
//        }
        String dateStr = request.getHeader("date");



        if(StringUtils.isBlank(dateStr)){
            try{
                Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                String data = getData(request);
                ApiRequestDTO requestDTO = gson.fromJson(data,ApiRequestDTO.class);
                ApiResponseDTO apiResponseDTO = new ApiResponseDTO(HttpStatus.SC_FORBIDDEN, "access denied", requestDTO.getUuid());
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                PrintWriter out = response.getWriter();
                out.append(gson.toJson(apiResponseDTO));
                return false;
            }
            catch (Exception e){
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        String rsaPrivateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAINWJeGSRyRW43ID0JR3ZQw8bvCSyhN52ZJXZaQL0Pt/LjrFgilpRRG3b/ODrkKsQ1qXlmP5w7pLwNSE8GXadJ+d9huewgVm+2CH3fDZS14cu+SsfPjeVbOWOh4+8CUBAqzWoHDYltZWi46dAwsmMs0RxuVsY+j9fH3ImCiIo+4XAgMBAAECgYA9UhC3xDtxLRxe1Icjeqd0UhcePfsZos/B8wpi0J2Pfy8Pg74lJaB5CCO+F+JaAOIlvxcZsLkBF3N+Bl/Tvm6qlzrjqepnN8/boT4hKvWNwYq5XQcs4i12cPVRLZsvVgFh1+yRvTDeLfBCNJxSxJWnWKBkCEb3k2mbZiXj6oE/WQJBANEW24bbCRGeRJmT58UmVaqekYU9oFIaxNwQYhqZoUEFhYVYDc61FLR/VjbykN2bc8jBN3bPoHbn8GuiIWYHkeUCQQCgzYXpYprUuRnhVxeAXWpwdDnqD27TAY9KGUCQbWWc7ZoXj2+qU08TNv709MPuyLGWzCF1aoUgvotOnEYYuHBLAkBJ7mAfFfHl9eVhvGeWUVC3LKxdxYWbonV7LpvRtgLLn+0vUgxHy8WPcPsGIMzSXvYYxSEcdJvTj312QXS3w/N1AkEAiuY9AAYevBVP16hFMqp+oLikthuynS3Buj3p2VfF6DINYsCRskzYBz8AKFOtU3ukex/E3wmuCUTOTI8MtZnL1QJAFBBAzxCVYdS7bw2CerSITYdf/v2Ev5yxUCY5YVqqzkPm9AWe4plype3y5Ub2xs2HoyigmYWf2cl8NkexJ0cniA==";
        RSAPrivateKey key = RSA.getPrivateKey(rsaPrivateKey);
        String timeStampStr = RSA.privateDecrypt(dateStr, key);
        Calendar cal = Calendar.getInstance();
        Date dateNow = cal.getTime();

        cal.setTimeInMillis(Long.parseLong(timeStampStr));
        cal.add(Calendar.SECOND, 10);
        Date reqDate = cal.getTime();
        System.out.println("reqDate+5s:" + reqDate);
        System.out.println("dateNow:" + dateNow);
        System.out.println("reqDate>dateNow:" + (reqDate.getTime() > dateNow.getTime()));
        System.out.println("reqDate<dateNow:" + (reqDate.getTime() < dateNow.getTime()));
        System.out.println("reqDate==dateNow:" + (reqDate == dateNow));
        if(reqDate.getTime() < dateNow.getTime()){
           try{
               Gson gson = new GsonBuilder().disableHtmlEscaping().create();
               String data = getData(request);
               ApiRequestDTO requestDTO = gson.fromJson(data,ApiRequestDTO.class);
               ApiResponseDTO apiResponseDTO = new ApiResponseDTO(HttpStatus.SC_FORBIDDEN, "access denied", requestDTO.getUuid());
               response.setCharacterEncoding("UTF-8");
               response.setContentType("application/json; charset=utf-8");
               PrintWriter out = response.getWriter();
               out.append(gson.toJson(apiResponseDTO));
                return false;
            }
            catch (Exception e){
                e.printStackTrace();
                response.sendError(500);
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        Calendar cal = Calendar.getInstance();
        Long timeStamp = cal.getTimeInMillis();
        System.out.println(timeStamp.toString());
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCDViXhkkckVuNyA9CUd2UMPG7wksoTedmSV2WkC9D7fy46xYIpaUURt2/zg65CrENal5Zj+cO6S8DUhPBl2nSfnfYbnsIFZvtgh93w2UteHLvkrHz43lWzljoePvAlAQKs1qBw2JbWVouOnQMLJjLNEcblbGPo/Xx9yJgoiKPuFwIDAQAB";
        RSAPublicKey key = null;
        try {
            key = RSA.getPublicKey(publicKey);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
        System.out.println(RSA.publicEncrypt("1536056567717",key));

    }

    /**
     *
     * @Description: TODO 获取请求传输过来的数据
     * @param @param req
     * @param @return
     * @param @throws IOException
     * @return String
     * @throws
     */
    private String getData(HttpServletRequest req) throws IOException {
        // 获取post参数
        StringBuffer sb = new StringBuffer();
        InputStream is = req.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String s = "";
        while ((s = br.readLine()) != null) {
            sb.append(s);
        }
        return  sb.toString();
    }
}
